﻿using System.Collections.Generic;
using System.Globalization;
using System.Xml;
using BHS.TFSChangsetAnalyser.Model;

namespace BHS.TFSChangsetAnalyser.Export
{
    public class XmlChangesetInfoExporter : IChangesetInfoExporter
    {
        public void ExportDataToFile(string filename, List<ChangesetInfo> changesetInfos)
        {
            XmlDocument doc = CreateXmlDocument(changesetInfos);
            doc.Save(filename);
        }

        public XmlDocument CreateXmlDocument(List<ChangesetInfo> changesetInfos)
        {
            XmlDocument doc = new XmlDocument();
            XmlNode rootNode = doc.CreateElement("ChangesetInfos");
            doc.AppendChild(rootNode);

            foreach (ChangesetInfo changesetInfo in changesetInfos)
            {
                XmlNode changesetNode = doc.CreateElement("Changeset");

                XmlNode changesetIdNode = doc.CreateElement("ChangesetID");
                changesetIdNode.InnerText = changesetInfo.ChangesetId.ToString(CultureInfo.InvariantCulture);
                changesetNode.AppendChild(changesetIdNode);

                XmlNode dateNode = doc.CreateElement("Date");
                dateNode.InnerText = changesetInfo.SubmittedDate.ToString(CultureInfo.CurrentCulture);
                changesetNode.AppendChild(dateNode);

                XmlNode submitterNode = doc.CreateElement("Submitter");
                submitterNode.InnerText = changesetInfo.Submitter;
                changesetNode.AppendChild(submitterNode);

                XmlNode commentsNode = doc.CreateElement("Comments");
                commentsNode.InnerText = changesetInfo.Comment;
                changesetNode.AppendChild(commentsNode);

                XmlNode nbrChangesNode = doc.CreateElement("NbrChanges");
                nbrChangesNode.InnerText = changesetInfo.NumberOfChanges.ToString(CultureInfo.InvariantCulture);
                changesetNode.AppendChild(nbrChangesNode);

                XmlNode nbrReviewableChangesNode = doc.CreateElement("NbrReviewableChanges");
                nbrReviewableChangesNode.InnerText = changesetInfo.NumberOfReviewableChanges.ToString(CultureInfo.InvariantCulture);
                changesetNode.AppendChild(nbrReviewableChangesNode);

                XmlNode reviewerNode = doc.CreateElement("CodeReviewer");
                reviewerNode.InnerText = changesetInfo.CodeReviewer;
                changesetNode.AppendChild(reviewerNode);

                XmlNode reviewStatusNode = doc.CreateElement("ReviewStatus");
                reviewStatusNode.InnerText = changesetInfo.WasCodeReviewed ? "Reviewed" : "Not Reviewed";
                changesetNode.AppendChild(reviewStatusNode);

                rootNode.AppendChild(changesetNode);
            }
            
            return doc;
        }
    }
}
